package org.example.nio_demo;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * @ClassName DemoPipe
 * @Description
 * @Author zhangsw
 * @Date 2020/11/14 11:15
 * @Version 1.0
 */
public class DemoPipe {
    @Test
    public void testPipe() throws IOException {
        //获取管道
        Pipe pipe = Pipe.open();
        //将缓冲区的数据写入管道
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Pipe.SinkChannel sinkChannel = pipe.sink();
        buffer.put("通过单向管道发送数据".getBytes());
        buffer.flip();
        sinkChannel.write(buffer);

        //读取缓冲区的数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        buffer.flip();
        int len = sourceChannel.read(buffer);
        System.err.println(new String(buffer.array(), 0, len));
        sourceChannel.close();
        sinkChannel.close();
    }
}
